<template>
  <div class="booking-list">
    <el-card class="booking-card">
      <template #header>
        <div class="card-header">
          <span>课程预约列表</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="已取消" :value="0" />
              <el-option label="待确认" :value="1" />
              <el-option label="已确认" :value="2" />
              <el-option label="已完成" :value="3" />
              <el-option label="已过期" :value="4" />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入会员姓名或课程名称"
              style="width: 300px; margin-right: 10px"
              clearable
              :maxlength="200"
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">创建预约</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="bookingList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="memberName" label="会员姓名" width="120" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="coachName" label="教练" width="120" />
        <el-table-column prop="bookingDate" label="预约日期" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="100" />
        <el-table-column prop="endTime" label="结束时间" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="primary"
              @click="handleConfirm(scope.row)"
            >
              确认
            </el-button>
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 2"
              size="small"
              type="warning"
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button
              v-if="scope.row.status !== 0 && scope.row.status !== 3 && scope.row.status !== 4"
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建预约对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="创建课程预约"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="bookingFormRef"
        :model="bookingForm"
        :rules="bookingRules"
        label-width="100px"
      >
        <el-form-item label="会员" prop="memberId">
          <el-select
            v-model="bookingForm.memberId"
            placeholder="请选择会员"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="member in memberList"
              :key="member.id"
              :label="`${member.name} (${member.phone})`"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select
            v-model="bookingForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
            @change="handleCourseChange"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教练" prop="coachId">
          <el-select
            v-model="bookingForm.coachId"
            placeholder="请选择教练"
            style="width: 100%"
          >
            <el-option
              v-for="coach in coachList"
              :key="coach.id"
              :label="coach.name"
              :value="coach.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="bookingDate">
          <el-date-picker
            v-model="bookingForm.bookingDate"
            type="date"
            placeholder="请选择预约日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="时间安排" prop="scheduleId">
          <el-select
            v-model="bookingForm.scheduleId"
            placeholder="请选择时间安排"
            style="width: 100%"
            @change="handleScheduleChange"
          >
            <el-option
              v-for="schedule in scheduleList"
              :key="schedule.id"
              :label="`${schedule.startTime} - ${schedule.endTime} (${schedule.bookedCount}/${schedule.capacity})`"
              :value="schedule.id"
              :disabled="!schedule.available"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  Booking,
  CreateBookingRequest,
  CourseSchedule
} from '@/types/api/booking'
import type { Member } from '@/types/api/member'
import type { Course } from '@/types/api/course'
import type { Coach } from '@/types/api/coach'
import { bookingApi } from '@/api/modules/booking'
import { memberApi } from '@/api/modules/member'
import { courseApi } from '@/api/modules/course'
import { coachApi } from '@/api/modules/coach'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const bookingList = ref<Booking[]>([])
const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const saveLoading = ref(false)
const bookingFormRef = ref()

// 下拉列表数据
const memberList = ref<Member[]>([])
const courseList = ref<Course[]>([])
const coachList = ref<Coach[]>([])
const scheduleList = ref<CourseSchedule[]>([])

// 表单数据
const bookingForm = reactive({
  memberId: undefined as number | undefined,
  courseId: undefined as number | undefined,
  coachId: undefined as number | undefined,
  bookingDate: '',
  scheduleId: undefined as number | undefined
})

// 表单验证规则
const bookingRules = {
  memberId: [
    { required: true, message: '请选择会员', trigger: 'change' }
  ],
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  coachId: [
    { required: true, message: '请选择教练', trigger: 'change' }
  ],
  bookingDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  scheduleId: [
    { required: true, message: '请选择时间安排', trigger: 'change' }
  ]
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 0: return 'danger'  // 已取消
    case 1: return 'warning' // 待确认
    case 2: return 'success' // 已确认
    case 3: return 'info'    // 已完成
    case 4: return 'info'    // 已过期
    default: return 'info'
  }
}

// 格式化状态显示
const formatStatus = (status: number) => {
  switch (status) {
    case 0: return '已取消'
    case 1: return '待确认'
    case 2: return '已确认'
    case 3: return '已完成'
    case 4: return '已过期'
    default: return '未知'
  }
}

// 禁用日期（过去日期不可选）
const disabledDate = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date.getTime() < today.getTime()
}

// 获取课程预约列表
const getBookingList = async () => {
  loading.value = true
  try {
    const response = await bookingApi.getBookingList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    bookingList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取课程预约列表失败')
  } finally {
    loading.value = false
  }
}

// 获取会员列表
const getMemberList = async () => {
  try {
    const response = await memberApi.getMemberList({
      page: 1,
      pageSize: 1000 // 获取所有会员
    })
    memberList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取会员列表失败')
  }
}

// 获取课程列表
const getCourseList = async () => {
  try {
    const response = await courseApi.getCourseList({
      page: 1,
      pageSize: 1000 // 获取所有课程
    })
    courseList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 获取教练列表
const getCoachList = async () => {
  try {
    const response = await coachApi.getCoachList({
      page: 1,
      pageSize: 1000 // 获取所有教练
    })
    coachList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取教练列表失败')
  }
}

// 获取课程时间安排
const getCourseSchedules = async () => {
  if (!bookingForm.courseId || !bookingForm.bookingDate) return

  try {
    const response = await bookingApi.getCourseSchedules({
      courseId: bookingForm.courseId,
      date: bookingForm.bookingDate
    })
    scheduleList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取课程时间安排失败')
  }
}

// 课程选择改变时
const handleCourseChange = () => {
  bookingForm.coachId = undefined
  bookingForm.scheduleId = undefined
  scheduleList.value = []
}

// 时间安排选择改变时
const handleScheduleChange = (scheduleId: number) => {
  const schedule = scheduleList.value.find(s => s.id === scheduleId)
  if (schedule) {
    bookingForm.coachId = schedule.coachId
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getBookingList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  pagination.page = 1
  getBookingList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getBookingList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getBookingList()
}

// 创建预约
const handleAdd = () => {
  dialogVisible.value = true
  // 重置表单
  Object.assign(bookingForm, {
    memberId: undefined,
    courseId: undefined,
    coachId: undefined,
    bookingDate: '',
    scheduleId: undefined
  })
  // 获取下拉列表数据
  getMemberList()
  getCourseList()
  getCoachList()
}

// 查看预约详情
const handleView = (row: Booking) => {
  ElMessage.info('查看预约详情功能待实现')
}

// 确认预约
const handleConfirm = (row: Booking) => {
  formUtils.handleDeleteConfirm(`会员 "${row.memberName}" 的预约`, async () => {
    await bookingApi.confirmBooking(row.id)
    getBookingList()
  }, {
    title: '确认预约',
    successMessage: '确认成功',
    errorMessage: '确认失败'
  })
}

// 取消预约
const handleCancel = (row: Booking) => {
  formUtils.handleDeleteConfirm(`会员 "${row.memberName}" 的预约`, async () => {
    await bookingApi.cancelBooking(row.id)
    getBookingList()
  }, {
    title: '取消预约',
    successMessage: '取消成功',
    errorMessage: '取消失败'
  })
}

// 删除预约
const handleDelete = (row: Booking) => {
  formUtils.handleDeleteConfirm(`会员 "${row.memberName}" 的预约记录`, async () => {
    await bookingApi.deleteBooking(row.id)
    getBookingList()
  }, {
    title: '确认删除',
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存预约信息
const handleSave = async () => {
  if (!bookingFormRef.value) return

  await bookingFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit('create_booking', async () => {
        saveLoading.value = true
        try {
          // 获取选中的时间安排
          const selectedSchedule = scheduleList.value.find(s => s.id === bookingForm.scheduleId)
          if (!selectedSchedule) {
            ElMessage.error('请选择有效的时间安排')
            return
          }

          // 创建预约
          const createData: CreateBookingRequest = {
            memberId: bookingForm.memberId!,
            courseId: bookingForm.courseId!,
            coachId: selectedSchedule.coachId,
            bookingDate: bookingForm.bookingDate,
            startTime: selectedSchedule.startTime,
            endTime: selectedSchedule.endTime
          }

          await bookingApi.createBooking(createData)
          ElMessage.success('创建成功')
          dialogVisible.value = false
          getBookingList()
        } catch (error: any) {
          ElMessage.error('创建失败')
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          saveLoading.value = false
        }
      })
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(bookingFormRef.value, bookingForm, {
    memberId: undefined,
    courseId: undefined,
    coachId: undefined,
    bookingDate: '',
    scheduleId: undefined
  })
}

// 初始化
onMounted(() => {
  getBookingList()
})
</script>

<style scoped lang="scss">
.booking-list {
  .booking-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
